let firstMenu = null;
export default function mapMenusToRoutes(menus) {
  const routes = [];

  const allRoutes = [];
  const routeFiles = require.context("../router/main", true, /\.js/);
  routeFiles.keys().forEach((key) => {
    const route = require("../router/main" + key.split(".")[1]);
    allRoutes.push(route.default);
  });
  const _recurseGetRoute = (menus) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const route = allRoutes.find((route) => route.path === menu.url);
        if (route) routes.push(route);
        if (!firstMenu) {
          firstMenu = menu;
        }
      } else {
        _recurseGetRoute(menu.children);
      }
    }
  };

  _recurseGetRoute(menus);

  return routes;
}

export function pathMapTobread(userMenus, currentPah) {
  const breadcrumbs = [];
  pathMapTOMenu(userMenus, currentPah, breadcrumbs);
  return breadcrumbs;
}

export function pathMapTOMenu(userMenus, currentPah, breadcrumbs = null) {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapTOMenu(menu.children ?? [], currentPah);
      if (findMenu) {
        breadcrumbs?.push({ name: menu.name, path: menu.url });
        breadcrumbs?.push({ name: findMenu.name, path: findMenu.url });
        return findMenu;
      }
    } else if (menu.type === 2 && menu.url === currentPah) {
      return menu;
    }
  }
  return breadcrumbs;
}
export { firstMenu };
